package twentytwentyone_3;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: Zahi
 * @Description:
 * @Date Created in 2021-03-25 14:54
 * @Modified By:
 */
public class FloodFill_733 {
    public static void main(String[] args){
        System.out.println(Arrays.deepToString(BFS(new int[][]{{1, 1, 1}, {1, 1, 0}, {1, 0, 1}}, 1, 1, 2)));
    }

//    public int[][] floodFill(int[][] image,int sr, int sc, int newColor){
//
//    }

    // BFS
    public static int[][] BFS(int[][] image,int sr, int sc, int newColor){

        int[] dx = {1, 0, 0, -1};
        int[] dy = {0, 1, -1, 0};

        // 定义初始位置的颜色
        int currColor = image[sr][sc];

        // 特殊条件
        if (currColor == newColor) {
            return image;
        }

        int n = image.length, m = image[0].length;
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{sr, sc});
        image[sr][sc] = newColor;
        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            int x = cell[0], y = cell[1];
            for (int i = 0; i < 4; i++) {
                int mx = x + dx[i], my = y + dy[i];
                if (mx >= 0 && mx < n && my >= 0 && my < m && image[mx][my] == currColor) {
                    queue.offer(new int[]{mx, my});
                    image[mx][my] = newColor;
                }
            }
        }
        return image;
    }
}
